package com.alienware.carlauncherlite.Dock;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;

import com.alienware.carlauncherlite.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

public class DockItemManager {
    public static final String allAppItemName = "所有应用";
    public static final String sponsorItemName = "赞助";
    public static final String customConfigName = "custom_dock";
    private static final HashMap<String, Integer> allAppsHashMap = new HashMap<String, Integer>();
    private static final HashSet<String> dockAppHashSet = new HashSet<String>();

    public static HashSet<String> GetDockAppHashSet() {
        return dockAppHashSet;
    }

    /**
     * 初始化替换图标HashMap
     */
    public static void InitAllAppHashMap() {
        //主页
        allAppsHashMap.put("com.android.settings", R.drawable.icon_ios_setting);//安卓设置
        allAppsHashMap.put("com.xyauto.Settings", R.drawable.icon_ios_setting2);//车载设置
        allAppsHashMap.put("com.xygala.canbus", R.drawable.icon_ios_setting3);//原车设置
        allAppsHashMap.put("com.autonavi.amapauto", R.drawable.icon_ios_map);//高德地图
        allAppsHashMap.put("com.netease.cloudmusic.iot", R.drawable.icon_ios_music);//网易云
        allAppsHashMap.put("com.mediatek.filemanager", R.drawable.icon_ios_file);//文件管理
        allAppsHashMap.put("com.autochips.bluetooth", R.drawable.icon_ios_bluetooth);//蓝牙
        allAppsHashMap.put("com.android.fmradio", R.drawable.icon_ios_sock_market);//收音机
        allAppsHashMap.put("com.acloud.stub.speech", R.drawable.icon_ios_memo3);//智能机器人

        //安卓原生
        allAppsHashMap.put("com.android.documentsui", R.drawable.icon_ios_file);//安卓文件
        allAppsHashMap.put("com.android.browser", R.drawable.icon_ios_browser);//浏览器
        allAppsHashMap.put("com.android.contacts", R.drawable.icon_ios_memo2);//通讯录
        allAppsHashMap.put("com.android.calendar", R.drawable.icon_ios_calendar2);//日历
        allAppsHashMap.put("com.android.gallery3d", R.drawable.icon_ios_photo);//图库
        allAppsHashMap.put("com.android.phone", R.drawable.icon_ios_phone);//电话
        allAppsHashMap.put("com.android.calculator2", R.drawable.icon_ios_calculator);//计算器
        allAppsHashMap.put("com.android.camera", R.drawable.icon_ios_camera);//相机
        allAppsHashMap.put("com.mediatek.camera", R.drawable.icon_ios_camera);//相机
    }

    /**
     * @param context 上下文
     */
    public static void InitDockAppHashSet(Context context) {
        if (checkFirstInstall(context)) {
            dockAppHashSet.add("com.autonavi.amapauto");//高德地图
            dockAppHashSet.add("com.netease.cloudmusic.iot");//网易云
            dockAppHashSet.add("com.android.settings");//安卓设置
            dockAppHashSet.add("com.autochips.bluetooth");//蓝牙
            dockAppHashSet.add("com.xyauto.Settings");//车载设置
            dockAppHashSet.add("com.xygala.canbus");//原车设置
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                dockAppHashSet.forEach(packageName -> {
                    setCustomDockItem(context, packageName, true);
                });
            } else {
                for (String packageName : dockAppHashSet) {
                    setCustomDockItem(context, packageName, true);
                }
            }
            setFirstInstall(context);
        }


        for (DockItemInfo dockItemInfo : GetAllAppList(context)) {
            if (getCustomDockItem(context, dockItemInfo.getPackageName())) {
                dockAppHashSet.add(dockItemInfo.getPackageName());
            }
        }
    }

    /**
     * @param context 上下文
     * @return 获取设备上所有的App列表
     */
    public static List<DockItemInfo> GetAllAppList(Context context) {
        //初始化替换图标
        InitAllAppHashMap();
        //获取所有应用列表
        List<DockItemInfo> list = new ArrayList<DockItemInfo>();
        PackageManager packageManager = context.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        @SuppressLint("QueryPermissionsNeeded") List<ResolveInfo> activities = packageManager.queryIntentActivities(mainIntent, 0);
        for (ResolveInfo info : activities) {
            String packageName = info.activityInfo.packageName;
            if (packageName.equals(context.getPackageName())) {
                continue;
            }
            DockItemInfo dockItemInfo = new DockItemInfo();
            dockItemInfo.setPackageName(packageName);
            dockItemInfo.setAppName(info.activityInfo.applicationInfo.loadLabel(packageManager).toString());
            dockItemInfo.setAppIcon(DockItemInfo.drawableToBitmap(info.activityInfo.applicationInfo.loadIcon(packageManager)));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                dockItemInfo.setChangeIcon(allAppsHashMap.getOrDefault(packageName, 0));
            } else {
                if (allAppsHashMap.containsKey(packageName)) {
                    dockItemInfo.setChangeIcon(allAppsHashMap.get(packageName));
                } else {
                    dockItemInfo.setChangeIcon(0);
                }
            }
            Intent launchIntent = new Intent();
            launchIntent.setComponent(new ComponentName(packageName, info.activityInfo.name));
            dockItemInfo.setIntent(launchIntent);
            list.add(dockItemInfo);
        }

        DockItemInfo allApps = new DockItemInfo();
        allApps.setPackageName(sponsorItemName);
        allApps.setAppName(sponsorItemName);
        allApps.setAppIcon(null);
        allApps.setChangeIcon(R.drawable.icon_ios_wallet);
        allApps.setIntent(null);
        list.add(allApps);

        return list;
    }

    /**
     * @param context 上下文
     * @return 获取Dock要显示的App列表，以HashSet为筛选条件
     */
    public static List<DockItemInfo> GetDockAppList(Context context) {
        //初始化DockItem
        InitDockAppHashSet(context);

        List<DockItemInfo> list = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            list = GetAllAppList(context).stream().filter(dockItemInfo -> dockAppHashSet.contains(dockItemInfo.getPackageName())).collect(Collectors.toList());
        } else {
            list = new ArrayList<DockItemInfo>();
            for (DockItemInfo dockItemInfo : GetAllAppList(context)) {
                if (dockAppHashSet.contains(dockItemInfo.getPackageName())) {
                    list.add(dockItemInfo);
                }
            }
        }

        DockItemInfo allApps = new DockItemInfo();
        allApps.setPackageName(allAppItemName);
        allApps.setAppName(allAppItemName);
        allApps.setAppIcon(null);
        allApps.setChangeIcon(R.drawable.icon_ios_appstore);
        allApps.setIntent(null);
        list.add(allApps);

        return list;
    }

    /**
     * @param context     上下文
     * @param packageName 包名
     * @return add成功执行保存本地数据、更新HashSet并返回true，否则直接返回false
     */
    public static boolean addDockItem(Context context, String packageName) {
        if (dockAppHashSet.contains(packageName)) {
            return false;
        } else {
            setCustomDockItem(context, packageName, true);
            dockAppHashSet.add(packageName);
            return true;
        }
    }

    /**
     * @param context     上下文
     * @param packageName 包名
     * @return remove成功执行保存本地数据、更新HashSet并返回true，否则直接返回false
     */
    public static boolean removeDockItem(Context context, String packageName) {
        if (dockAppHashSet.contains(packageName)) {
            setCustomDockItem(context, packageName, false);
            dockAppHashSet.remove(packageName);
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param context     上下文
     * @param packageName 包名
     * @return 读取本地数据，对应包名是否显示在Dock
     */
    public static boolean getCustomDockItem(Context context, String packageName) {
        //获得SharedPreferences的实例
        SharedPreferences sharedPreferences = context.getSharedPreferences(customConfigName, Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean(packageName, false);
    }

    /**
     * @param context      上下文
     * @param packageName  包名
     * @param showDockItem 修改对应包名是否显示在Dock
     */
    public static void setCustomDockItem(Context context, String packageName, boolean showDockItem) {
        //获得SharedPreferences的实例
        SharedPreferences sharedPreferences = context.getSharedPreferences(customConfigName, Context.MODE_PRIVATE);
        //获得Editor 实例
        SharedPreferences.Editor editor = sharedPreferences.edit();
        //以key-value形式保存数据
        editor.putBoolean(packageName, showDockItem);
        editor.apply();//异步写入数据
//        editor.commit();//同步写入数据
    }

    /**
     * 设置此App第一次安装
     *
     * @param context 上下文
     */
    public static void setFirstInstall(Context context) {
        if (checkFirstInstall(context)) {
            //获得SharedPreferences的实例
            SharedPreferences sharedPreferences = context.getSharedPreferences(customConfigName, Context.MODE_PRIVATE);
            //获得Editor 实例
            SharedPreferences.Editor editor = sharedPreferences.edit();
            //以key-value形式保存数据
            editor.putBoolean("first_install", false);
            editor.apply();//异步写入数据
        }

    }

    /**
     * @param context 上下文
     * @return 检查此App是否第一次安装
     */
    public static boolean checkFirstInstall(Context context) {
        //获得SharedPreferences的实例
        SharedPreferences sharedPreferences = context.getSharedPreferences(customConfigName, Context.MODE_PRIVATE);
        return sharedPreferences.getBoolean("first_install", true);
    }
}